package com.sea.product.controller;

import com.codecrane.core.power.service.DictDetailService;
import com.codecrane.core.power.service.PowerGroupService;
import com.codecrane.core.util.DateUtils;
import com.codecrane.core.util.ExcelUtil;
import com.codecrane.core.util.NewProductStatusEnum;
import com.codecrane.core.web.Ajax;
import com.codecrane.core.web.AjaxReturn;
import com.codecrane.core.web.AjaxTableReturn;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sea.product.entity.NewProduct;
import com.sea.product.entity.Product;
import com.sea.product.service.CategoryService;
import com.sea.product.service.ChannelService;
import com.sea.product.service.NewProductService;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.List;


@Controller
@RequestMapping(value = "/sea/product/new")
public class NewProductController {
    @Autowired
    private DictDetailService dictDetailService;
    @Autowired
    private ChannelService channelService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private PowerGroupService powerGroupService;
    @Autowired
    private NewProductService newProductService;
    /**
     * 管理主页面
     * @param model
     * @return
     */
    @RequestMapping("/main")
    public String main(Model model) {
        getModel(model);
        return "/sea/product/newProduct/main";
    }
    /**
     * 新增页面
     *
     * @param model
     * @return
     */
    @RequestMapping("/addPage")
    public String addPage(Model model) {
        getModel(model);
        return "/sea/product/newProduct/add";
    }

    void getModel(Model model){
        //国家
        model.addAttribute("country", dictDetailService.findByTypeCode("base_country", null));
        model.addAttribute("brand", dictDetailService.findByTypeCode("base_brand", null));
        model.addAttribute("channel", channelService.findByCnd(null));
        model.addAttribute("category",categoryService.findCategory());
        model.addAttribute("group",powerGroupService.findByPid(3));
    }


    /**
     * 分页条件查询
     *
     * @param pagesize
     * @param start
     * @return
     */
    @ResponseBody
    @RequestMapping("/findByCnd")
    public AjaxTableReturn findByCnd(@RequestParam(value = "limit", defaultValue = "10") int pagesize,
                                     @RequestParam(value = "offset", defaultValue = "0") int start,
                                     NewProduct product
    ) {
        start = start > 0 ? start / pagesize + 1 : 1;
        PageHelper.startPage(start, pagesize);
        List<NewProduct> list = newProductService.findByCnd(product);
        PageInfo<NewProduct> page = new PageInfo<>(list);
        return Ajax.tableDataOk(page.getTotal(), page.getList());
    }


    /**
     * 保存
     * @param product
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public AjaxReturn save(NewProduct product) {
        AjaxReturn result = Ajax.fail().setMsg("保存失败！");
        try{
            if (null != product && newProductService.save(product) > 0) {
                result.setOk(true).setMsg("保存成功！");
            }
        }catch (Exception e){
            e.printStackTrace();
            result.setMsg("系统异常,请联系管理员!");
            return result;
        }
        return result;
    }

    @RequestMapping(value = "/export", method = RequestMethod.GET)
    @ResponseBody
    public void export(HttpServletResponse response, NewProduct newProduct) {
        List<NewProduct> list = newProductService.export(newProduct);
        String[] title = {"国家","渠道", "品牌","部门","商品名称","大类","中类","小类","状态"
                ,"预计完成(企划)","实际完成(企划)"
                ,"预计完成(来样)","实际完成(来样)"
                ,"预计完成(评审)","实际完成(评审)"
                ,"预计完成(建档)","实际完成(建档)"
                ,"预计完成(下单)","实际完成(下单)"
                ,"预计完成(出运)","实际完成(出运)"
                ,"预计完成(上新)","实际完成(上新)"};

        String fileName = "上新信息" + DateUtils.dateToString(new Date(), "yyyyMMdd") + ".xls";
        String sheetName = "上新信息";
        String[][] content = new String[list.size()][23];
        for (int i = 0; i < list.size(); i++) {
            content[i] = new String[title.length];
            NewProduct obj = list.get(i);
            content[i][0] = obj.getProductCountry();
            content[i][1] = obj.getProductChannelName();
            content[i][2] = obj.getProductBrand();
            content[i][3] = obj.getProductGroup();
            content[i][4] = obj.getProductName();
            content[i][5] = obj.getProductBigClassName();
            content[i][6] = obj.getProductMidClassName();
            content[i][7] = obj.getProductClassName();
            content[i][8] = NewProductStatusEnum.getStatus(obj.getProductStatus());
            content[i][9] = obj.getProduct_one_time();
            content[i][10] = obj.getProduct_one_date();
            content[i][11] = obj.getProduct_two_time();
            content[i][12] = obj.getProduct_two_date();
            content[i][13] = obj.getProduct_three_time();
            content[i][14] = obj.getProduct_three_date();
            content[i][15] = obj.getProduct_four_time();
            content[i][16] = obj.getProduct_four_date();
            content[i][17] = obj.getProduct_five_time();
            content[i][18] = obj.getProduct_five_date();
            content[i][19] = obj.getProduct_six_time();
            content[i][20] = obj.getProduct_six_date();
            content[i][21] = obj.getProduct_seven_time();
            content[i][22] = obj.getProduct_seven_date();
        }
        //创建HSSFWorkbook
        HSSFWorkbook wb = ExcelUtil.getHSSFWorkbook(sheetName, title, content, null);
        //响应到客户端
        try {
            this.setResponseHeader(response, fileName);
            OutputStream os = response.getOutputStream();
            wb.write(os);
            os.flush();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //发送响应流方法
    public void setResponseHeader(HttpServletResponse response, String fileName) {
        try {
            try {
                fileName = new String(fileName.getBytes(), "ISO8859-1");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            response.setContentType("application/octet-stream;charset=ISO8859-1");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            response.addHeader("Pargam", "no-cache");
            response.addHeader("Cache-Control", "no-cache");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}
